import 'package:permission_handler/permission_handler.dart';

import '../utils.dart';

class PermissionUtil{

  static Future<bool> isLocationServiceOn() async{
    return await Permission.location.serviceStatus.isEnabled;
  }

  static Map<String, bool> cache = {};
  static Future<bool> checkPermissions(List<Permissions> permissions, String desc) async{
    bool hasPermission = true;
    String key = permissions.map((e) => e.name).join(',');
    Log.log('key $key');
    if(cache[key]??false){
      Log.log('cache true');
      return true;
    }
    Map<Permission, PermissionStatus> statuses =
    await permissions.map((e) => e.value).toList().request();
    statuses.forEach((key, value) {
      Log.log('$key $value');
      if(!value.isGranted){
        hasPermission = false;
        return;
      }
    });
    cache.update(key, (value) => hasPermission, ifAbsent: () => hasPermission);
    if(!hasPermission){
      showPermissionDialog(desc);
    }
    return hasPermission;
  }

  static bool hasShowPermissionDialog = false;
  static showPermissionDialog(String desc){
    if(hasShowPermissionDialog){
      return;
    }
    hasShowPermissionDialog = true;
    DialogUtil.defaultDialog('', desc, confirmCallback: (){
      openAppSettings();
    }).then((value) => hasShowPermissionDialog = false);
  }

  static toAppSetting() {
    openAppSettings();
  }

  static Future<bool> checkPermissionsStatus(List<Permissions> permissions) async{
    bool flag = true;
    for (var element in permissions) {
      if((await element.value.status) != PermissionStatus.granted){
        flag = false;
        break;
      }
    }
    return flag;
  }
}

enum Permissions{
  location(Permission.location),
  bluetoothScan(Permission.bluetoothScan),
  bluetoothConnect(Permission.bluetoothConnect),
  phoneState(Permission.phone),
  bluetooth(Permission.bluetooth),
  sms(Permission.sms),
  calendar(Permission.calendarFullAccess),
  contacts(Permission.contacts),
  batteryOptimize(Permission.ignoreBatteryOptimizations),
  camera(Permission.camera),
  microphone(Permission.microphone),
  mediaLibrary(Permission.mediaLibrary),
  photosAddOnly(Permission.photosAddOnly),
  photos(Permission.photos),
  storage(Permission.storage),
  queryPackages(Permission.requestInstallPackages);

  final Permission value;
  const Permissions(this.value);
}